package com.sr365.changan.infrastructure.service.base;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sr365.changan.infrastructure.dao.CommonDao;
import com.sr365.changan.infrastructure.domain.AbstractBaseDomain;
import com.sr365.changan.infrastructure.service.BaseDomainService;
import com.sr365.changan.utils.reflect.ReflectionUtils;

/**
 * Created by WangXingchao.
 * User: WangXingchao (wangxingchao@gmail.com)
 * Date: 2010-6-7
 * Time: 17:43:54
 * Description: Basic Service Class.
 */
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class CommonDomainService<T extends AbstractBaseDomain> implements BaseDomainService<T> {
    @Autowired
    protected CommonDao commonDao;

    private Class<T> clazz;

    @SuppressWarnings("unchecked")
    public CommonDomainService() {
        this.clazz = ReflectionUtils.getSuperClassGenericType(getClass());
    }

    /**
     * Load a object by id.
     * @param id
     * @return
     */
    public T load(Long id) {
        return id == null ? null : commonDao.load(clazz, id);
    }

    /**
     * Load a object by a regular property and its value.
     * @param propertyName
     * @param propertyValue
     * @return
     */
    public T load(String propertyName, Object propertyValue) {
        return commonDao.load(clazz, propertyName, propertyValue);
    }

    /**
     * Load a object by a set properties and their appropriate values.
     * @param propertyNames
     * @param propertyValues
     * @return
     */
    public T load(String[] propertyNames, Object[] propertyValues) {
        return commonDao.load(clazz, propertyNames, propertyValues);
    }

    /**
     * Query all objects.
     * @param orderProperties
     * @return
     */
    public List<T> findAll(String... orderProperties) {
        return commonDao.findAll(clazz, orderProperties);
    }

    /**
     * Query objects by a property and its value.
     * @param propertyName
     * @param propertyValue
     * @return
     */
    public List<T> find(String propertyName, Object propertyValue) {
        return commonDao.find(clazz, propertyName, propertyValue);
    }

    /**
     * Query objects by a set properties and their appropriate values.
     * @param propertyNames
     * @param propertyValues
     * @return
     */
    public List<T> find(String[] propertyNames, Object[] propertyValues) {
        return commonDao.find(clazz, propertyNames, propertyValues);
    }

    /**
     * Save or Update a object.
     * @param o
     */
    @Transactional(readOnly = false)
    public void save(T o) {
        commonDao.save(o);
    }
}

